package com.soup.lab.tools.faker.source;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * 直接将文件行读取到内存中
 */
public class SmallFileSourceReader implements SourceReader<String> {

    private final ReaderSource readerSource;

    private List<String> list;

    public SmallFileSourceReader(ReaderSource readerSource) {
        this.readerSource = Objects.requireNonNull(readerSource);
    }

    @Override
    public synchronized Iterator<String> iterator() {
        if (list == null) {
            initList();
        }
        return list.iterator();
    }

    public synchronized Stream<String> getAsStream() {
        if(list == null) {
            initList();
        }
        return list.stream();
    }

    private void initList() {
        try (BufferedReader reader = readerSource.getAsReader()) {
            list = new ArrayList<>();
            String line;
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            list = new ArrayList<>();
        }

    }

}
